package cc.mcyx.ychat.controller

import cc.mcyx.ychat.service.UserService
import cn.hutool.core.date.DateUtil
import cn.hutool.core.io.FileUtil
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.multipart.MultipartFile
import util.md5Str

@RestController
@RequestMapping("api/upload")
@ResponseBody
@Api("上传", tags = ["上传文件处理"])
open class UploadController {

    @Autowired
    lateinit var userService: UserService

    @Value("\${ychat.public}")
    lateinit var publicPath: String

    @PostMapping("profile")
    @ApiOperation("更新用户头像")
    fun uploadFile(@RequestParam("file") multipartFile: MultipartFile): String {
        val user = userService.getCurrentUser()
        // 将文件进行存储
        val md5 = md5Str(multipartFile.bytes)
        val date = DateUtil.date()
        val path = "profile/${date.year()}/${date.month()}/${date.dayOfMonth()}/${md5}.jpg"
        FileUtil.writeBytes(multipartFile.bytes, "${publicPath}/${path}")
        return "public/${path}".also {
            user.profile = it
            userService.updateById(user)
        }
    }
}